package com.qf.xiaomi.dao.impl;

import com.qf.xiaomi.dao.AddressDao;
import com.qf.xiaomi.pojo.TbAddress;
import com.qf.xiaomi.utils.DButils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    QueryRunner queryRunner = new QueryRunner(DButils.getdataSource());

    @Override
    public int addAddress(TbAddress tbAddress) {
        String sql = "insert into tb_address (detail,name,phone,uid) values (?,?,?,?)";
        try {
            int update = queryRunner.update(sql, tbAddress.getDetail(),tbAddress.getName(),tbAddress.getPhone(),tbAddress.getUid());
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<TbAddress> selectAddress(long uid) {
        String sql = "select * from tb_address where uid=?";
        try {
            List<TbAddress> list = queryRunner.query(sql, new BeanListHandler<>(TbAddress.class),uid);
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public TbAddress selectById(long aid) {
        String sql = "select * from tb_address where id=?";
        try {
            TbAddress address = queryRunner.query(sql, new BeanHandler<>(TbAddress.class),aid);
            return address;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public int deleteById(long aid) {
        String sql = "delete from tb_address where id = ?";
        try {
            int update = queryRunner.update(sql,aid);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateAdress(TbAddress tbAddress) {
        String sql = "update tb_address set detail=? ,name=? ,phone=? ,uid=? where id=? ";
        try {
            int update = queryRunner.update(sql, tbAddress.getDetail(), tbAddress.getName(), tbAddress.getPhone(), tbAddress.getUid(), tbAddress.getId());
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int setDefault(TbAddress tbAddress) {
        String sql="update tb_address set level=? where id=?";
        try {
            int update = queryRunner.update(sql, tbAddress.getLevel(), tbAddress.getId());
            System.out.println("更新"+update);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
